package com.stars.easyms.mq.core.activemq;

import com.stars.easyms.mq.core.MQMessageSender;
import com.stars.easyms.mq.dto.MQSendResult;
import com.stars.easyms.mq.properties.EasyMsMQProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.connection.JmsResourceHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Session;

/**
 * ActiveMQ消息发送者
 *
 * @author guoguifang
 * @date 2018-04-23 13:54
 * @since 1.0.0
 */
public class ActiveMQMessageSender implements MQMessageSender {

    private final Logger logger = LoggerFactory.getLogger(ActiveMQMessageSender.class);

    private ActiveMQTemplateFactory activeMQTemplateFactory;

    private ConnectionFactory connectionFactory;

    private EasyMsMQProperties easyMsMQProperties;

    @Override
    public MQSendResult convertAndSend(String currentSendKey, String message, String destinationType, Boolean currMessIsAllowNonPersistent) {
        registerMQSenderSession();
        ActiveMQTemplate activeMQTemplate = activeMQTemplateFactory.getActiveMQTemplate(connectionFactory, easyMsMQProperties, destinationType, currMessIsAllowNonPersistent);
        activeMQTemplate.convertAndSend(currentSendKey, message);
        return MQSendResult.from(true);
    }

    private void registerMQSenderSession() {
        // 注册MQ发送事务资源
        try {
            if (TransactionSynchronizationManager.getResource(connectionFactory) == null) {
                Connection connection = connectionFactory.createConnection();
                connection.start();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                TransactionSynchronizationManager.bindResource(connectionFactory, new JmsResourceHolder(connectionFactory, connection, session));
            }
        } catch (Exception e) {
            logger.error("注册MQ发送事务资源失败!", e);
        }
    }

    public ActiveMQMessageSender(ApplicationContext applicationContext, EasyMsMQProperties easyMsMQProperties) {
        this.easyMsMQProperties = easyMsMQProperties;
        this.connectionFactory = BasicActiveMQConnectionFactory.getActiveMQConnectionFactory(applicationContext, easyMsMQProperties);
        this.activeMQTemplateFactory = new ActiveMQTemplateFactory();
    }

}
